<?php
ini_set('include_path', dirname(__FILE__ ) . '/../Lapa' . ';' .ini_get('include_path'));

require_once('../Lapa/Engine/Parser.php');

class LapaTest extends LapaEngineBase 
{
    private $parser;
    private $php_output;
    
    public $time;
    
    public function __construct()
    {
        $this->parser   = new LapaEngineParser();
    }
    
    public function eTime()
    {
        echo $this->time;
    }
    
    public function eCode()
    {
        highlight_string($this->php_output);
    }
    
    public function testString($strTemplate, $compilePath, $paramsVars = null)
    {
        $time = microtime(1);
        $this->php_output = $this->parser->parse('', $strTemplate);
        $this->time = microtime(1) - $time;
        
        self::writeFile($this->php_output, $compilePath);
        
        return $this->execCompileFile($compilePath, $paramsVars);
        
    }
    
    public function eTest($strTemplate, $compilePath, $paramsVars = null)
    {
        echo '--- result ---<br />';
        echo $this->testString($strTemplate, $compilePath, $paramsVars);
        echo '<br />--- /result ---';
        printf('<br /> ---$Parser->parse %1.6f --- <br />', $this->time);
        echo '--- php ---<br />';
        $this->eCode();
    }
    
    private function execCompileFile($compilePath, $paramsVars)
    {
        $_var_local = array();    
        if ( is_array($paramsVars) && count(($paramsVars) ) > 0) {
            $_var = & $paramsVars;
        }else {
            $_var = array();
        }
    
        ob_start();
        require($compilePath);
        $res = ob_get_contents(); ob_get_clean(); 
      
        return $res;
    }
    
    private static function writeFile(& $source, $compilePath)
    {
        if ( function_exists('get_magic_quotes_runtime') ) {$lv = get_magic_quotes_runtime(); set_magic_quotes_runtime(0);}
    
        $result = false; $try = true;
        
        $dir = dirname($compilePath);
        if ( file_exists($dir) && ($tmp = tempnam($dir, 'le')) ) {
            $res = file_put_contents($tmp, $source);
            if ( !@rename($tmp, $compilePath) ) {
                @unlink($compilePath);
                if ( @rename($tmp, $compilePath) ) {
                    $result = true;
                }
            }else {
                $result = true;
            }
        }

        if ( function_exists('set_magic_quotes_runtime') ) set_magic_quotes_runtime($lv);
        return $result;
    }
    


}


$LapaTest = new LapaTest();